package com.woniuxy.interceptor;

import com.woniuxy.annotations.RequirePerm;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

//认证权限注解的拦截器: 识别方法的注解，判断当前登录用户有没有这个权限或者角色
@Component
public class AuthPermInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // handler判断是部署一个方法：排除静态资源访问
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //判断该方法是否存在这个注解
            if (method.isAnnotationPresent(RequirePerm.class)) {
                //获取controller上对应的注解标注的参数值："order::add", "order::edit"
                RequirePerm annotation = method.getAnnotation(RequirePerm.class);
                String[] perms = annotation.perms();
                for (String perm : perms) {
                    //获取请求头的token，去数据库查询对应用户的权限，根据权限列表遍历比较
                    if (perm.equals(request.getHeader("perm"))) {   //满足，放行
                        return true;
                    }
                }
            }else {
                //如果不需要判断权限，也应该放行
                return true;
            }
        }else {
            return true;
        }
        //所有权限比较都失败
        response.setStatus(500);
        return false;
    }
}
